/**
 * @file Define Weibo service
 * 
 * @author Steve Gao<gaofu@parllay.com>
 */
const async                 = require('async');

const utils                 = require('../utils');
const redisKey              = require('../redisKey');
const BaseService           = require('./base-service').BaseService;
const WeiboAPI              = require('../apis/weibo-api').WeiboAPI;
const WeChatMessageHelper   = require('../helpers/wechat-helpers').WeChatMessageHelper;

const {SystemServices, Configuration}        = require('../constants');

class WeiboService extends BaseService {

    get weiboConfig() {
        return this.getApplicationConfiguration(Configuration.WEIBO);
    }

    get wallService() {
        return this.getSystemService(SystemServices.WALL_SERVICE);
    }

    /**
     * Get weibo OAuth2 redirect url
     * 
     * @name getWeiboRedirectURL
     * @param {IncomingMessage} request - The request object
     * @param {Function} parentCallback - The callback function
     * 
     * @returns {void}
     */
    getWeiboRedirectURL(request, parentCallback) {
        let weiboConfig = this.weiboConfig;

        parentCallback(`https://api.weibo.com/oauth2/authorize?client_id=${weiboConfig.app_key}&redirect_uri=${weiboConfig.authorized_callback}&response_type=code`);
    }

    handleWeiboAuthorization(params, userId, parentCallback) {
        if (!params.code) {
            return parentCallback({
                success: false,
                error: '授权失败'
            });
        }

        var me = this;

        let weiboConfig = this.weiboConfig;

        let parameters = {
            client_id: weiboConfig.app_key,
            client_secret: weiboConfig.app_secret,
            grant_type: 'authorization_code',
            code: params.code,
            redirect_uri: weiboConfig.authorized_callback
        };

        async.waterfall([
            (callback) => {
                WeiboAPI.getAccessToken(parameters, (error, data) => {
                    if (error) {
                        parentCallback({
                            success: false,
                            error: error.message
                        });
                    } else {
                        callback(null, data);
                    }
                });
            },
            (data, callback) => {
                if (!data.access_token) {
                    parentCallback({
                        success: false,
                        error: '添加微博账号时出现错误，请稍后再试！'
                    })
                } else {
                    WeiboAPI.getUserInfo(data.access_token, data.uid, (error, user) => {
                        callback(null, data, user);
                    });
                }
            },
            (data, user, callback) => {
                var account = {
                    user_id: userId,
                    app_id: user.idstr,
                    name: user.name,
                    logo: user.profile_image_url,
                    metadata: user,
                    access_token: data.access_token,
                    verify_type: user.verified_type,
                    type: 'oauth',
                    social_type: 'weibo'
                };

                me.wallService.saveOrUpdateAccount(userId, account, (error, data) => {
                    if (error) {
                        parentCallback({
                            success: false,
                            error: error
                        });
                    } else {
                        parentCallback({
                            success: true,
                            data: data
                        });
                    }
                });
            }
        ])
        
    }
}

exports.WeiboService = WeiboService;